package top.kaoshanji.r3ch11a;

/**
 * 代码清单-r3ch11a-365页a：一个ThreadLocal实例
 * @author kaoshanji
 * ^_^
 * create time 2025/5/8 18:39
 */
public class SequenceNumber {

    // 通过匿名内部类覆盖 ThreadLocal 的 initialValue() 方法，指定初始值
    private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){

        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    // 获取下一个序列值
    public int getNextNum() {
        seqNum.set(seqNum.get() + 1);
        return seqNum.get();
    }

    public static void main(String[] args) {
        SequenceNumber sn = new SequenceNumber();

        // 3个线程共享sn，各自产生序列号
        ClientTest t1 = new ClientTest(sn);
        ClientTest t2 = new ClientTest(sn);
        ClientTest t3 = new ClientTest(sn);

        t1.start();
        t2.start();
        t3.start();

    }




}
